package com.example.apidocserver.infrastructure.util.pdf;

import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.HorizontalAlignment;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.VerticalAlignment;
import org.apache.poi.xwpf.usermodel.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import static com.itextpdf.layout.properties.TextAlignment.CENTER;

public class WordToPdfUtil {
    public static void toPdf(XWPFDocument document, String outPath) throws IOException {
        // 创建 PDF 文档
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(Files.newOutputStream(Paths.get(outPath))));
        Document pdfDocLayout = new Document(pdfDoc);
        pdfDoc.setDefaultPageSize(PageSize.A4);

        PdfFont font = PdfFontUtil.getPdfFont();
        // 遍历 Word 文档中的段落
        for (XWPFParagraph paragraph : document.getParagraphs()) {
            // 将段落内容添加到 PDF 文档中
            Paragraph pdfP = new Paragraph(paragraph.getText());
            pdfP.setTextAlignment(TextAlignment.LEFT);
            pdfP.setFontSize(12f);

            for (XWPFRun run : paragraph.getRuns()) {
                String text = run.getText(0);
                if (text != null) {
                    pdfP.add(text);
                    pdfP.setFontSize(run.getFontSize());
                    pdfP.setFont(font);
                    if (run.isBold()) {
                        pdfP.setBold();
                    }
                    if (run.isItalic()) {
                        pdfP.setItalic();
                    }
                }
            }


            pdfDocLayout.add(pdfP);
        }

        // 遍历 Word 文档中的表格
        for (XWPFTable table : document.getTables()) {
            // 将表格内容添加到 PDF 文档中
            Table pdfTableLayout = new Table(table.getNumberOfRows());
            pdfTableLayout.setHorizontalAlignment(HorizontalAlignment.CENTER);
            pdfTableLayout.setVerticalAlignment(VerticalAlignment.MIDDLE);

            for (int i = 0; i < table.getNumberOfRows(); i++) {
                for (int j = 0; j < table.getRow(i).getTableCells().size(); j++) {

                    XWPFTableCell cell = table.getRow(i).getCell(j);
                    Paragraph paragraph = new Paragraph(cell.getText()).setTextAlignment(CENTER);
                    paragraph.setFont(font);
                    paragraph.setFontSize(cell.getParagraphs().size());
                    pdfTableLayout.addCell(paragraph);
                }
            }
            pdfDocLayout.add(pdfTableLayout);
        }

        // 关闭文档
        pdfDoc.close();
    }

}

